<template>
  <a-form
    :model="formState"
    name="basic"
    :label-col="{ span: 8 }"
    :wrapper-col="{ span: 16 }"
    autocomplete="off"
    @finish="onFinish"
    @finishFailed="onFinishFailed"
  >
    <a-form-item
      label="account"
      name="account"
      :rules="[{ required: true, message: 'Please input your account!' }]"
    >
      <a-input v-model:value="formState.account" />
    </a-form-item>

    <a-form-item
      label="Password"
      name="password"
      :rules="[{ required: true, message: 'Please input your password!' }]"
    >
      <a-input-password v-model:value="formState.password" />
    </a-form-item>

    <a-form-item
      label="Username"
      name="captchaCode"
      :rules="[{ required: true, message: 'captchaCode' }]"
    >
      <a-input v-model:value="formState.captchaCode" />
      <div v-html="captcha.svg"></div>
    </a-form-item>

    <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
      <a-button type="primary" html-type="submit">Submit</a-button>
    </a-form-item>
  </a-form>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { getCaptchaApi, loginApi } from '@/api/auth.api.ts'
import { useAuthStore } from '@/stores/auth.ts'
import { useRouter } from 'vue-router'

interface FormState {
  account: string
  password: string
  captchaCode: string
}

const formState = reactive<FormState>({
  account: '',
  password: '',
  captchaCode: '',
})

const router = useRouter()
const onFinish = (values: any) => {
  loginApi({ ...values, captchaId: captcha.value.captchaId }).then((res) => {
    useAuthStore().login(res.user, {
      accessToken: res.access_token,
      refreshToken: res.refresh_token,
    })
    router.replace('/role')
  })
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo)
}

const captcha = ref({
  svg: '',
  captchaId: '',
})
const getCaptcha = () => {
  getCaptchaApi().then((res) => {
    captcha.value = res
  })
}
getCaptcha()
defineOptions({
  name: 'LoginPage',
})
</script>
